package com.ruoyi.web.service.impl;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.CodeLogin;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.QRCodeUtils;
import com.ruoyi.common.utils.SHA512Util;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.service.IScanCodeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class ScanCodeServiceImpl implements IScanCodeService {
    @Resource
    private RedisCache redisCache;
    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysLoginService sysLoginService;

    @Resource
    private SysPermissionService permissionService;
    @Resource
    private TokenService tokenService;


    @Override
    public AjaxResult checkLoginStatus(String token) {
        AjaxResult success = AjaxResult.success();
        //查询redis状态
        String redisRes = redisCache.getCacheObject(CacheConstants.SCAN_CODE_LOGIN_KEY + token);
        if (redisRes == null) {
            //已过期
            success.put("qrCodeStatus", CodeLogin.EXPIRATION.getCode());
            return success;
        }
        String[] split = redisRes.split("-");
        if (split.length == 1) {
            //待确认未扫描
            success.put("qrCodeStatus", CodeLogin.NOT_SCANNED.getCode());
            return success;
        }
        if (split.length != 2) {
            throw new GlobalException("扫码登录token格式错误");
        }
        String status = split[0];
        Long userId = Long.parseLong(split[1]);
        if (Objects.isNull(status)) {
            throw new GlobalException("扫码登录token格式错误");
        }
        if (Objects.equals(CodeLogin.SUCCESS.getCode(), status)) {
            //根据userId获取登录token，走正常的登录逻辑返回给PC
            SysUser user = sysUserMapper.selectUserById(userId);
            LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
            sysLoginService.recordLoginInfo(userId);

            String resToken = tokenService.createToken(loginUser);
            //清除扫码key缓存
            redisCache.deleteObject(CacheConstants.SCAN_CODE_LOGIN_KEY + ":" + token);

            success.put("qrCodeStatus", CodeLogin.SUCCESS.getCode());
            success.put("accessToken", resToken);
            return success;
        }
        throw new GlobalException("扫码登录token格式错误");
    }

    @Override
    public AjaxResult getAll(String t) {
        //校验token时间是否超过5秒
        //根据秒数生成临时token
        String token = SHA512Util.generateSHA512Hash(UUID.fastUUID().toString());

        redisCache.setCacheObject(CacheConstants.SCAN_CODE_LOGIN_KEY + token, CodeLogin.NOT_SCANNED.getCode(), 50, TimeUnit.SECONDS);

        //返回token和携带token的图片base64
        AjaxResult res = new AjaxResult();
        res.put("qrCodeToken", token);
        res.put("codeBase64", QRCodeUtils.generateQRCodeBase64(token, 300, 300));
        return res;
    }
}
